﻿using System;
using System.IO;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace eStock.Common
{
    static class Extentions
    {
        public static byte[] ToByteArray(this Image img)
        {
            var bmp = img.Source as BitmapImage;

            if (bmp != null)
            {
                MemoryStream memStream = new MemoryStream();
                JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bmp));
                encoder.Save(memStream);
                return memStream.GetBuffer();

            }
            throw new Exception("Failed to convert Image to byte[]");
        }
        public static string Right(this string value, int length)
        {
            return value.Substring(value.Length - length);
        }
        public static BitmapImage ToImage(this byte[] bytes)
        {
            try
            {
                
                MemoryStream byteStream = new MemoryStream(bytes);
                BitmapImage image = new BitmapImage();
                image.BeginInit();
                image.StreamSource = byteStream;
                image.EndInit();

                return image;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public static void NextStep(this ProgressBar bar, int amount = 1)
        {
            if(!bar.Dispatcher.CheckAccess())
            {
                bar.Dispatcher.Invoke(new Action(() => NextStep(bar, amount)));
                return;
            }
            bar.Value += amount;
        }

        public static int GetIndexByTag(this ComboBox cb, object tagVal)
        {
            for(int i=0; i < cb.Items.Count; i++)
            {
                if (!(cb.Items[i] is ComboBoxItem)) continue;
                if (((ComboBoxItem)cb.Items[i]).Tag == tagVal)
                    return i;
            }
            return -1;
        }
        public static string Hex2String(this string hex)
        {
            string result = "";
            hex = hex.Replace("%5C%5Cx", "");
            int count = hex.Length / 2;
            int s;

            for (s = 0; s < count; s++)
            {
                string zeichen = hex.Substring(s * 2, 2);
                result += (char)Convert.ToUInt16(zeichen, 16);
            }

            return result;
        }
    }
}
